﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gift.Utile;
using Gift.Model;
using Gift.DAL;
using System.Web.Security;
using System.Data;

namespace WebSite.admin.company
{
    public partial class companyManager : BaseAdmin
    {
        readonly dalCompany theCompany = new dalCompany();
        readonly DALAdminLogin theAdminLogin = new DALAdminLogin();
        readonly UserRuleRef theUserRuleRef = new UserRuleRef();
        readonly DALRule theRule = new DALRule();
        readonly DALRegion theRegion = new DALRegion();
        public int ParaCompanyId
        {
            get
            {
                if (string.IsNullOrEmpty(Request.QueryString["id"]))
                {
                    return -1;
                }
                else
                {
                    return int.Parse(Request.QueryString["id"]);
                }
            }
        }
        public string Action
        {
            get
            {
                return Request.QueryString["action"];

            }
        }

        string ParamentType
        {
            get
            {
                if (string.IsNullOrEmpty(Request.QueryString["type"]))
                {
                    return string.Empty;
                }
                else
                {
                    return Request.QueryString["type"];
                }
            }
        }


        public void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (ParamentType == "publish")
                {
                    this.ddlUpCompany.Hidden = true;
                    this.ddlCompanyLevel.Enabled = false;
                    base.ValidateLoginRule(Gift.Model.ENUM.ERule.AddPublishCompany);
                }
                else if (base.CompanyId == null)
                {
                    base.ValidateLoginRule(Gift.Model.ENUM.ERule.AddCompany);
                }

                if (ParaCompanyId > -1 && base.CompanyId != null)
                {
                    this.txtName.Enabled = false;
                    this.txtShortName.Enabled = false;
                    this.txtCompanyCode.Enabled = false;
                    this.txtManager.Enabled = false;
                    this.txtManagerMobile.Enabled = false;
                    this.ddlSheng.Enabled = false;
                    this.ddlShi.Enabled = false;
                    this.txtAddress.Enabled = false;
                    this.ddlUpCompany.Enabled = false;
                    this.ddlCompanyLevel.Enabled = false;
                    this.ddlSalesman.Enabled = false;
                    tbCompany oCompany = theCompany.GetModel(ParaCompanyId);
                    if (oCompany.ParentId.ToString() == base.CompanyId)
                    {
                        this.txtOnSale.Enabled = true;
                        this.txtCreditMoney.Enabled = true;
                    }
                    else
                    {
                        this.txtOnSale.Enabled = false;
                        this.txtCreditMoney.Enabled = false;
                    }

                }
                if (base.AdminTypeId == ((int)Gift.Model.ENUM.EAdminType.Salesman).ToString())
                {
                    this.form1.Disabled = true;
                }

                this.BindCompanyList();
                this.BindCompanyLevel();
                this.BindPrivence();
                this.BindCity();
                this.BindArea();
               this.BuildForm();
                if (ParaCompanyId < 0)
                {
                    this.BindSalesmanList();
                }

            }
        }


        protected void chk1_CheckedChanged(object sender, EventArgs e)
        {
            if (this.chk1.Checked)
            {
                this.txtLinker.Text = this.txtManager.Text;
                this.txtMobile.Text = this.txtManagerMobile.Text;
            }

        }

        void BuildForm()
        {
            if (Action == "del")
            {
                if (base.CompanyId != null && base.CompanyId == ParaCompanyId.ToString())
                {
                    ExtAspNet.Alert.Show("不能删除自己！");
                    base.Response.End();
                }
                else
                {
                    if (theCompany.ExistsDownCompany(ParaCompanyId))
                    {
                        ExtAspNet.Alert.Show("您有下级商家，如要删除，请先删除下级商家！");
                        base.Response.End();
                    }
                    else
                    {
                        theCompany.Delete(ParaCompanyId);
                        ExtAspNet.Alert.Show("删除成功！", "", "window.location.href='companyList.aspx';");
                        base.Response.End();
                    }
                }
            }

            else if (ParaCompanyId >= 0)
            {
                tbCompany oCompany;
                oCompany = theCompany.GetModel(ParaCompanyId);
                if (theCompany != null)
                {
                    if (base.CompanyId != null)
                    {
                        this.txtAddress.Text = oCompany.Provence + "," + oCompany.Area + "," + oCompany.Address;
                    }
                    else
                    {
                        this.txtAddress.Text = oCompany.Address;
                    }
                    this.txtEmail.Text = oCompany.Email;
                    this.txtFax.Text = oCompany.Fax;
                    this.txtLinker.Text = oCompany.Linker;
                    this.txtName.Text = oCompany.Name;
                    this.hdCompany.Text = oCompany.Name;
                    this.txtPostcode.Text = oCompany.Postcode;
                    this.txtQQ.Text = oCompany.QQ;
                    this.txtTel.Text = oCompany.Telephone;
                    if (this.ddlCompanyCategory.Items.FindByValue(oCompany.CompanyTypeId.ToString()).Selected == false)
                    {
                        this.ddlCompanyCategory.SelectedValue = oCompany.CompanyTypeId.ToString();
                    }
                    if (oCompany.LevelId == 0)
                    {
                         this.ddlCompanyLevel.Items.Insert(0, new ExtAspNet.ListItem("顶级", "0"));
                    }
                    this.ddlCompanyLevel.Items.FindByValue(oCompany.LevelId.ToString()).Selected = true;

                    this.txtOnSale.Text = theCompany.GetCompanyOnSale(oCompany.Id.ToString()).ToString();
                    this.txtCreditMoney.Text = oCompany.CreditMoney.ToString();
                    this.txtMobile.Text = oCompany.Mobile;
                    this.txtCompanyCode.Text = oCompany.CompanyCode;
                    this.txtShortName.Text = oCompany.CompanyShortName;
                    this.txtManager.Text = oCompany.CompanyManager;
                    this.txtManagerMobile.Text = oCompany.CompanyManagerMobile;

                    if (this.ddlUpCompany.Items.FindByValue(oCompany.ParentId.ToString()) != null)
                    {
                        this.ddlUpCompany.Items.FindByValue(oCompany.ParentId.ToString()).Selected = true;
                        this.BindSalesmanList();
                    }

                    if (oCompany.Salesman != string.Empty && this.ddlSalesman.Items.FindByValue(oCompany.Salesman) != null)
                    {
                        this.ddlSalesman.Items.FindByValue(oCompany.Salesman).Selected = true;
                    }

                    if (base.CompanyId == ParaCompanyId.ToString())
                    {
                        this.ddlCompanyLevel.Enabled = false;
                        this.txtOnSale.Enabled = false;
                        this.txtUserName.Text = base.AdminUser;

                    }
                    else
                    {
                        this.txtPassword.Hidden = true;
                        this.txtUserName.Hidden = true;
                        this.txtUserName.Required = false;
                        this.txtPassword.Required = false;
                    }
                    if (oCompany.LevelId == 1)
                    {
                        this.ddlCompanyLevel.Enabled = false;
                        this.ddlUpCompany.Hidden = false;
                        this.ddlUpCompany.Required = false;
                    }
                    if (this.ddlSheng.Items.FindByText(oCompany.Provence) != null)
                    {
                        this.ddlSheng.SelectedValue = this.ddlSheng.Items.FindByText(oCompany.Provence).Value;
                        this.BindCity();
                    }
                    if (this.ddlShi.Items.FindByText(oCompany.City) != null)
                    {
                        this.ddlShi.SelectedValue = this.ddlShi.Items.FindByText(oCompany.City).Value;
                        this.BindArea();
                    }
                    if (this.ddlXian.Items.FindByText(oCompany.Area) != null)
                    {
                        this.ddlXian.SelectedValue = this.ddlXian.Items.FindByText(oCompany.Area).Value;
                    }
                    this.txtUserName.Enabled = false;
     
                }
            }
            else
            {
                this.txtCompanyCode.Text = theCompany.GetGenerateCompanyCode(ParamentType == "publish").ToString();
            }
        }

        protected void btnSubmitForm1_Click(object sender, EventArgs e)
        {
            tbCompany oCompany;
            tbAdminlogin oAdminLogin;
            oCompany = null;
            if (ParaCompanyId > -1)
            {
                oCompany = theCompany.GetModel(ParaCompanyId);
            }

            if (oCompany == null) oCompany = new tbCompany();
            tbCompany oUpCompany = theCompany.GetModel(int.Parse(this.ddlUpCompany.SelectedItem.Value));

            try
            {
                double dSale = double.Parse(this.txtOnSale.Text.Trim());
                if ((dSale < 0.5 || dSale > 1.0) && base.CompanyLevelId != "0" && base.CompanyLevelId != "1")
                {
                    ExtAspNet.Alert.Show("折扣只能为0.50-1.00的数字！");
                    return;
                }
                else if (dSale < 0.2 || dSale > 1.0)
                {
                    ExtAspNet.Alert.Show("折扣只能为0.20-1.00的数字！");
                    return;
                }
            }
            catch
            {
                ExtAspNet.Alert.Show("折扣只能为0.50-1.00的数字！");
                return;
            }

            try
            {
                double dCreditMoney = double.Parse(this.txtCreditMoney.Text.Trim());
                if (dCreditMoney < 0)
                {
                    ExtAspNet.Alert.Show("授信额度只能为大于等于0的数字！");
                    return;
                }
            }
            catch
            {
                ExtAspNet.Alert.Show("授信额度只能为大于等于0的数字！");
                return;
            }
            oCompany.Id = ParaCompanyId;
            oCompany.Email = this.txtEmail.Text.Trim();
            oCompany.Linker = this.txtLinker.Text.Trim();
            oCompany.Fax = this.txtFax.Text.Trim();
            oCompany.Name = this.txtName.Text.Trim();
            oCompany.Postcode = this.txtPostcode.Text.Trim();
            oCompany.QQ = this.txtQQ.Text.Trim();
            oCompany.Telephone = this.txtTel.Text.Trim();
            if (ParamentType == "publish")
            {
                oCompany.ParentId = 0;
            }
            else
            {
                if ((oCompany.ParentId != 0 || ParaCompanyId == -1) && oCompany.ParentId != -1)
                {
                    oCompany.ParentId = this.ddlUpCompany.SelectedItem.Value == "" ? 0 : int.Parse(this.ddlUpCompany.SelectedItem.Value);
                }
            }
            oCompany.LevelId = int.Parse(this.ddlCompanyLevel.SelectedItem.Value);
            oCompany.Mobile = this.txtMobile.Text.Trim();
            oCompany.CompanyTypeId = int.Parse(this.ddlCompanyCategory.SelectedItem.Value);
            oCompany.CompanyCode = this.txtCompanyCode.Text.Trim();
            oCompany.CompanyShortName = this.txtShortName.Text.Trim();
            oCompany.CompanyManager = this.txtManager.Text.Trim();
            oCompany.CompanyManagerMobile = this.txtManagerMobile.Text.Trim();
            oCompany.CreditMoney = this.txtCreditMoney.Text.Trim() == "" ? 0 : decimal.Parse(this.txtCreditMoney.Text);
            oCompany.Provence = this.ddlSheng.SelectedItem.Text;
            oCompany.City = this.ddlShi.SelectedItem.Text;
            oCompany.Area = this.ddlXian.SelectedItem.Text;
            oCompany.Address = this.txtAddress.Text.Trim();
            try
            {
                if (ParaCompanyId >= 0)
                { 
                    if (theCompany.ExistsByCode(this.txtCompanyCode.Text.Trim()) && oCompany.CompanyCode != this.txtCompanyCode.Text.Trim())
                    {
                        ExtAspNet.Alert.Show("系统中已有此公司编码，请重新设置编码！");
                        this.txtCompanyCode.Text = theCompany.GetGenerateCompanyCode(ParamentType == "publish").ToString();
                        return;
                    }

                    if (this.hdCompany.Text != oCompany.Name)
                    {
                        tbCompany tempCompany = theCompany.GetModelByName(oCompany.Name);
                        if (tempCompany != null)
                        {
                            ExtAspNet.Alert.Show("该公司名已存在,请重新输入公司名！");
                            return;
                        }
                    }
                    if (oCompany.CompanyShortName != this.txtShortName.Text.Trim()
                         && theCompany.ExistsByShortName(this.txtShortName.Text.Trim()))
                    {
                        ExtAspNet.Alert.Show("该公司简称已存在,请重新输入公司简称！");
                        return;
                    }

                    if (oUpCompany.LevelId >= int.Parse(this.ddlCompanyLevel.SelectedItem.Value) )
                    {
                        ExtAspNet.Alert.Show("上级公司级别不能小于添加的公司级别！");
                        return;
                    }
                    oAdminLogin = new tbAdminlogin();
                    if (base.CompanyId == ParaCompanyId.ToString())
                    {
                        int iAdminId = theAdminLogin.GetIdByName(this.txtUserName.Text.Trim());

                        if (iAdminId <= 0)
                        {
                            oAdminLogin.AdminUser = this.txtUserName.Text.Trim();
                            oAdminLogin.AdminPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(re.replace(this.txtPassword.Text), "MD5");
                            iAdminId = theAdminLogin.Add(oAdminLogin);
                            oAdminLogin.AdminId = iAdminId;
                        }
                        else
                        {
                            oAdminLogin.AdminId = iAdminId;
                            oAdminLogin.AdminUser = this.txtUserName.Text.Trim();
                            if (!string.IsNullOrEmpty(this.txtPassword.Text.Trim()))
                            {
                                oAdminLogin.AdminPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(re.replace(this.txtPassword.Text), "MD5");
                                theAdminLogin.Update(oAdminLogin);
                            }
                        }
                    }
                    theCompany.Update(oCompany);
                    theCompany.IsExistsOnSale(oCompany.Id.ToString(), float.Parse(this.txtOnSale.Text.Trim()));
                }
                else
                {
                    oCompany.Provence = this.ddlSheng.SelectedItem.Value;
                    oCompany.City = this.ddlXian.SelectedItem.Value;
                    oCompany.Area = this.ddlShi.SelectedItem.Value;
                    oCompany.Address = this.txtAddress.Text.Trim();

                    tbCompany tempCompany = theCompany.GetModelByName(oCompany.Name);
                    if (tempCompany != null)
                    {
                        ExtAspNet.Alert.Show("该公司名已存在,请重新输入公司名！");
                        return;
                    }

                    if (theCompany.ExistsByShortName(this.txtShortName.Text.Trim()))
                    {
                        ExtAspNet.Alert.Show("该公司简称已存在,请重新输入公司简称！");
                        return;
                    }

                    if (theCompany.ExistsByCode(this.txtCompanyCode.Text.Trim()))
                    {
                        ExtAspNet.Alert.Show("系统中已有此公司编码，请重新设置编码！");
                        this.txtCompanyCode.Text = theCompany.GetGenerateCompanyCode(ParamentType == "publish").ToString();
                        return;
                    }
                    oAdminLogin = new tbAdminlogin();

                    int iAdminId = theAdminLogin.GetIdByName(this.txtUserName.Text.Trim());
                    if (iAdminId > 0)
                    {
                        ExtAspNet.Alert.Show("该用户名已存在,请重新输入用户名！");
                        return;
                    }

                    if (oUpCompany.LevelId >= int.Parse(this.ddlCompanyLevel.SelectedItem.Value) && oCompany.LevelId != 1)
                    {
                        ExtAspNet.Alert.Show("上级公司级别不能小于添加的公司级别！");
                        return;
                    }

                    if (this.txtPassword.Text.Trim() == "")
                    {
                        ExtAspNet.Alert.Show("密码不能为空！");
                        return;
                    }
                    oAdminLogin.AdminUser = this.txtUserName.Text.Trim();
                    oAdminLogin.AdminPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(re.replace(this.txtPassword.Text), "MD5");
                    iAdminId = theAdminLogin.Add(oAdminLogin);
                    theCompany.Add(oCompany);
                    DataSet ds = theRule.GetCompanyRuleList();
                    StringBuilder sbIds = new StringBuilder();
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        sbIds.Append("," + dr["id"].ToString());
                    }

                    theUserRuleRef.SaveCompanyRule(iAdminId, sbIds.ToString().Substring(1, sbIds.Length - 1));
                    oCompany = theCompany.GetModelByName(oCompany.Name);
                    SQLAccess.DoSql(string.Format("insert into tbCompanyAdmin(CompanyId,AdminId) values({0},{1});"
                                    , oCompany.Id, iAdminId.ToString()));
                    theCompany.IsExistsOnSale(oCompany.Id.ToString(), float.Parse(this.txtOnSale.Text.Trim()));
                }

                if (this.ddlSalesman.SelectedItem.Value != string.Empty)
                {
                    SQLAccess.DoSql(string.Format("delete tbCompanyAdmin where AdminId in(select AdminId from tbAdminLogin where AdminTypeId = 1) and CompanyId ={0} and isnull(AdminTypeId,0) = 0;  insert into tbCompanyAdmin(CompanyId,AdminId) values({0},{1});"
                                       , oCompany.Id, this.ddlSalesman.SelectedItem.Value));
                }
                if (Request.QueryString["ot"] == "ed")
                {
                    if (ParamentType == "publish")
                    {
                        ExtAspNet.Alert.Show("保存成功！", "", "openNewTab('PublishCompanyList','/admin/company/companyList.aspx?type=publish','发行商列表','CompanyEdit')");
                    }
                    else
                    {
                        ExtAspNet.Alert.Show("保存成功！", "", "openNewTab('CompanyList','/admin/company/companyList.aspx','商家列表','CompanyEdit')");
                    }
                }
                else
                {
                    if (ParamentType == "publish")
                    {
                        ExtAspNet.Alert.Show("保存成功！", "", "openNewTab('PublishCompanyList','/admin/company/companyList.aspx?type=publish','发行商列表','AddPublishCompany')");
                    }
                    else
                    {
                        ExtAspNet.Alert.Show("保存成功！", "", "openNewTab('CompanyList','/admin/company/companyList.aspx','商家列表','AddCompany')");
                    }
                }
  
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message.ToString());
            }
        }

        void BindSalesmanList()
        {
            this.ddlSalesman.Items.Clear();
            string sql = string.Format("select  a.AdminId,a.AdminName "
                                      + " from tbAdminLogin a join tbCompanyAdmin ca on a.AdminId = ca.AdminId "
                                      + " and a.AdminTypeId = ca.AdminTypeId "
                                      + " where a.adminTypeId = 1 and ca.CompanyId = {0} order by AdminName "
                                      , this.ddlUpCompany.SelectedItem == null ? "-1" : this.ddlUpCompany.SelectedItem.Value);
            DataSet ds = SQLAccess.GreatDs(sql);
            this.ddlSalesman.DataTextField = "AdminName";
            this.ddlSalesman.DataValueField = "AdminId";
            this.ddlSalesman.DataSource = ds;
            this.ddlSalesman.DataBind();
            this.ddlSalesman.Items.Insert(0, new ExtAspNet.ListItem("请选择业务员...", ""));
        }

        void BindCompanyLevel()
        {
            DataSet ds = theCompany.GetListForCompanyLevel();
            this.ddlCompanyLevel.DataTextField = "LevelName";
            this.ddlCompanyLevel.DataValueField = "Id";
            if (ds != null && ds.Tables.Count > 0)
            {
                if (ParamentType == "publish")
                {
                    ds.Tables[0].DefaultView.RowFilter = "Id =1";
                }
                else
                {
                    if (base.CompanyId == ParaCompanyId.ToString())
                    {
                        ds.Tables[0].DefaultView.RowFilter = "Id >=" + base.CompanyLevelId;
                    }
                    else
                    {
                        if (ParaCompanyId >= 0)
                        {
                            tbCompany oCompany = theCompany.GetModel(ParaCompanyId);
                             ds.Tables[0].DefaultView.RowFilter = "Id >=" + oCompany.LevelId;
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(base.CompanyId))
                            {
                                ds.Tables[0].DefaultView.RowFilter = "Id >=" + base.CompanyLevelId;
                            }
                            else
                            {
                                ds.Tables[0].DefaultView.RowFilter = "Id >1";
                            }
                        }

                     
                    }
                 
                }

                this.ddlCompanyLevel.DataSource = ds.Tables[0].DefaultView;
                this.ddlCompanyLevel.DataBind();
            }
        }

        void BindCompanyList()
        {
            DataTable dt;
            string sWhere = " 1=1 ";

            dt = theCompany.GetList(sWhere).Tables[0];
            if (base.CompanyId != null)
            {
                if (ParaCompanyId >= 0)
                {
                    dt = GetAllCompany(dt, null, 0, true);
                }
                else
                {
                    dt = GetAllCompany(dt, null, int.Parse(base.CompanyId), false);
                }
            }
            else
            {

                dt = GetAllCompany(dt, null, 0, true);
            }
            this.ddlUpCompany.DataTextField = "Name";
            this.ddlUpCompany.DataValueField = "Id";
            this.ddlUpCompany.DataSource = dt;
            this.ddlUpCompany.DataBind();

            if (ParaCompanyId < 0 && base.CompanyId != null)
            {
                this.ddlUpCompany.Items.FindByValue(base.CompanyId).Selected = true;
            }
        }

        protected void ddlUpCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindSalesmanList();
        }


        private void BindPrivence()
        {
            this.ddlSheng.Items.Clear();
            DataTable dtPrivence =theRegion.GetRegionByParentRegion(0);
            ddlSheng.DataTextField = "regionName";
            ddlSheng.DataValueField = "id";
            ddlSheng.DataSource = dtPrivence;
            ddlSheng.DataBind();

            ddlSheng.Items.Insert(0, new ExtAspNet.ListItem("选择省份", "-1"));
        }

        private void BindCity()
        {
            string sheng = ddlSheng.SelectedValue;
            this.ddlShi.Items.Clear();
            if (sheng != "-1")
            {
                DataTable dtCity = theRegion.GetRegionByParentRegion(int.Parse(sheng));
                this.ddlShi.DataTextField = "regionName";
                this.ddlShi.DataValueField = "id";
                ddlShi.DataSource = dtCity;
                ddlShi.DataBind();
            }

            ddlShi.Items.Insert(0, new ExtAspNet.ListItem("选择地区市", "-1"));
        }

        private void BindArea()
        {
            string shi = ddlShi.SelectedValue;
            this.ddlXian.Items.Clear();
            if (shi != "-1")
            {
                DataTable dtArea = theRegion.GetRegionByParentRegion(int.Parse(shi));
                this.ddlXian.DataTextField = "regionName";
                this.ddlXian.DataValueField = "id";
                ddlXian.DataSource = dtArea;
                ddlXian.DataBind();
            }
            if (ddlXian.Items.Count <= 0)
            {
                ddlXian.Items.Insert(0, new ExtAspNet.ListItem("选择地区市", ""));
            }
            else
            {
                ddlXian.Items.Insert(0, new ExtAspNet.ListItem("选择地区市", "-1"));
            }
        }

        protected void ddlSheng_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCity();
        }

        protected void ddlShi_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindArea();
        }

        public string HeaderHtml
        {
            get
            {
                if (!string.IsNullOrEmpty(Request.QueryString["id"]) && Request.QueryString["id"] != "0")
                {

                    tbCompany oCompany = theCompany.GetModel(int.Parse(Request.QueryString["id"]));

                    string sHead = string.Format(" <div  class=\"navgater\"><img src=\"../images/module.gif\" width=\"20\" height=\"22\" alt=\"\"/> "
                                              + " 公司名称：{0} "
                                              + " <a style=\" display:block; float:right;\" href=\"javascript:location.href='companyList.aspx?id={1}&type={2}';\" ><img src=\"../images/history.gif\" border=\"0\" /></a>"
                                              + " </div>"
                                              , oCompany.Name
                                              , oCompany.ParentId.ToString()
                                              , ParamentType);
                    return sHead;
                }
                return string.Empty;

            }


        }
    }
}